package com.sunlands.deskmate.message.handler.sender.http;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sunlands.deskmate.client.PushInformService;
import com.sunlands.deskmate.client.PushMessageService;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.entity.PushInformEntity;
import com.sunlands.deskmate.entity.PushMessageEntity;
import com.sunlands.deskmate.vo.response.BusinessResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static com.sunlands.deskmate.message.enums.MessageType.*;

@Slf4j
@Service
public class HttpMessagesSender {

    @Autowired
    private PushMessageService pushMessageService;

    @Autowired
    private PushInformService pushInformService;

    public void doPushInform(Messages msgEntity, List<Long> offlineUserIds) {
        // 推送通知
        PushInformEntity informEntity = new PushInformEntity();
        informEntity.setContent(msgEntity.getMessage());
        informEntity.setIds(offlineUserIds);
        informEntity.setType(1);
        log.info("push inform start entity={} ", informEntity);
        BusinessResult businessResult = pushInformService.pushInform(informEntity);
        log.info("push inform end result={}", businessResult);
    }

    public void doPushMessage(Messages msgEntity, List<Long> uIds) {
        String type = msgEntity.getType();
        if (type.startsWith("3")) {
            return;
        }
        PushMessageEntity messageEntity = new PushMessageEntity();
        messageEntity.setUserIds(uIds);
        messageEntity.setType(type);
        if (type.startsWith("1")) {
            messageEntity.setBusinessId(msgEntity.getFromUserId());
        } else {
            messageEntity.setBusinessId(msgEntity.getToId());
        }
        messageEntity.setContent(msgEntity.getMessage());
        messageEntity.setIsGroupSend(false);
        if (Objects.nonNull(msgEntity.getExtras())) {
            messageEntity.setExtras(JSONObject.parseObject(msgEntity.getExtras().toJSONString(), new TypeReference<Map<String, String>>() {
            }));
        }
        log.info("push message start entity={} ", messageEntity);
        BusinessResult businessResult = pushMessageService.pushMessage(messageEntity);
        log.info("push message end result={}", businessResult);
    }

    public boolean filterPushInform(String connectType) {
        return !(connectType.equals(group_user_join.getType())
                || connectType.equals(group_user_exit.getType())
                || connectType.equals(AgreeApplyPublish.getType())
                || connectType.equals(QuitPublish.getType())
                || connectType.equals(OperateAllMic.getType())
                || connectType.equals(OWN_MIC_OPERATION.getType())
        );
    }
}
